import React from 'react';
import _ from 'underscore';
import moment from 'moment';

import deepExtend from 'lib/util/deepExtend';
import Chart from 'lib/components/chart.jsx';
import DefaultErrorElement from 'lib/util/defaultErrorElement.jsx';
import DefaultNoDataElement from 'lib/util/defaultNoDataElement.jsx';
import DefaultLoadingElement from 'lib/util/defaultLoadingElement.jsx';

export default class ChartWidget extends React.Component{
  constructor(props, context) {
    super(props, context);

    this.getChartObject = this.getChartObject.bind(this);
  }

  getConfig() {
    return {
      chartOption:{
        height:this.props.height,
        type:this.props.chartType,
        zoomType:'x'
      },
      tooltip:{
        useHTML:true,
        shared:this.props.tooltipShared,
        formatter:this.props.tooltipFormat
      },
      chartSettings:deepExtend({
        chart:{
          events:{
            selection:this.props.onSelection
          }
        },
        plotOptions:{
          series:{
            cursor:this.props.onPointClick ? "pointer":'',
            point:{
              events:{
                click:this.props.onPointClick
              }
            }
          }
        }
      },this.props.chartSettings)
    };
  } // getConfig

  getChartObject() {
    return this.refs.originalChart;
  } // getChartObject

  renderChart(data){
    let config = this.getConfig();
    return (
      <Chart
        ref="originalChart"
        chart={config.chartOption}
        series={data.series}
        yAxis={data.yAxis}
        chartSettings={config.chartSettings}
        tooltip={config.tooltip}
      />
    )
  }
  renderLoading(){
    return <DefaultLoadingElement height={this.props.height} />
  }
  renderError(){
    return <DefaultErrorElement height={this.props.height} />
  }
  render(){

    if(this.props.store.loading){
      return this.renderLoading(this.props.store.params);
    }else if(this.props.store.error){
      return this.renderError(this.props.store.error)
    }else if(this.props.store.data){
      if(this.props.store.data.series.length){
        return this.renderChart(this.props.store.data);
      }else{
        return <DefaultNoDataElement height={this.props.height} />
      }
    }else{
      return null
    }
  }
}

var pattern = 'MM/DD HH:mm';
var tmplPrefix = '<div style="color:<%=serie.color%>; max-width: 320px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; display: inline-block;"><%=serie.name%></div>'
          +'<br/>'
          +'<span>'
  , pieTmplPrefix = '<div style="color:<%=point.color%>; max-width: 320px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; display: inline-block;"><%=point.name%></div>'
            +'<br/>'
            +'<span>'
  , tmplSuffix = '</span><br/>'

ChartWidget.defaultProps = {
  chartType:'line',
  height:200,
  onPointClick:null,
  onSelection:null,
  tooltipShared:false,
  tooltipFormat:function(tooltip){
    var tmpl
    if(this.point&&this.point.customData){
      tmpl = ''
        + (tooltip.chart.options.chart.type==='pie'?pieTmplPrefix:tmplPrefix)
        + ('从'
        + moment(this.point.customData.startTime).format(pattern)
        + '到'+moment(this.point.customData.endTime).format(pattern)
        + '的'+moment.duration(this.point.customData.endTime - this.point.customData.startTime).humanize()+'内')
        + tmplSuffix
        + _.map([this.point.customData.y].concat(
            _.chain(this.point.customData).omit('startTime','endTime','y').values().value()
          ),function(p){
            return '<span>'+p.label+'：</span><b>'+p.fmtVal+'</b>'
          }).join('<br />')
      return _.template(tmpl)({
        serie:this.series,
        point:this.point
      });
    }
    if(this.points&&this.points.length){
      var serieTmpl = _.template('<i class="iconfont  state-downtime" style="color:<%=series.color%>">●</i><%=customData.y.fmtVal%>(<%=series.name%>)<br />');

      tmpl = (
        '从'
      + moment(this.points[0].point.customData.startTime).format(pattern)
      + '到' + moment(this.points[0].point.customData.endTime).format(pattern)
      + '的' + moment.duration(this.points[0].point.customData.endTime - this.points[0].point.customData.startTime).humanize()
      + '内'
      + "<br/>"
      + _(this.points).map(function(item){ return serieTmpl(item.point) }).join('')
      )
      return _.template(tmpl)(this.points[0]);
    }
    return null
  },
  chartSettings:{}
}
